#!/opt/midware/python3/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2024/12/24 10:14
# @File    : ws_client.py
# @Software: PyCharm
# @version : python3.11
import asyncio
import websockets
import uuid
import json
import time

IP_ADDR = "127.0.0.1"
IP_PORT = "9090"

my_uuid = uuid.uuid4().__str__()
async def clientHands(websocket):
    while True:
        # 通过发送hello握手
        register_dict = {"type": "handshake"}
        await websocket.send(json.dumps(register_dict))
        response_str = await websocket.recv()
        # 接收"success"来进行双方的握手
        try:
            data = json.loads(response_str)
            print("clientHands response:", response_str)
        except Exception as e:
            print(f"{response_str} to json error: {e}")

        if data['type'] == "handshake":
            register_dict = {"type": "register", "uuid": my_uuid}
            await websocket.send(json.dumps(register_dict))
        elif data['type'] == "register":
            if 'user_list' in data.keys():
                if my_uuid in data.get('user_list'):
                    return True

async def ws_ping(websocket):
    # print(dir(websocket))
    ping_dict = {"type": "ping"}
    ping_message = json.dumps(ping_dict)
    while True:
        await asyncio.sleep(3)
        await websocket.send(ping_message)
        # time.sleep(3)

async def run_ping(websocket):
    asyncio.run(ws_ping(websocket))

# 向服务器端发送消息
async def clientSend(websocket):
    # from threading import Thread
    # thread = Thread(target=run_ping, args=(websocket,), daemon=True)
    # thread.start()
    while True:
        input_text = input("input text: ")
        if input_text == "exit":
            print(f'"exit", bye!')
            await websocket.close(reason="exit")
            return False
        message = str(eval(input_text))
        # '{"type": "send", "content": "just test"}'
        await websocket.send(message)
        print(f"clientSend input_text: {input_text}")
        recv_text = await websocket.recv()
        print(f"clientSend recv: {recv_text}")


# 进行websocket连接
async def clientRun():
    ipaddress = IP_ADDR + ":" + IP_PORT
    async with websockets.connect("ws://" + ipaddress) as websocket:
        await clientHands(websocket)
        # await clientSend(websocket)
        ping_task = asyncio.create_task(ws_ping(websocket))
        send_task = asyncio.create_task(clientSend(websocket))
        await asyncio.gather(ping_task, send_task)

        print(f"over")


# main function
if __name__ == '__main__':
    print("======client======")
    # asyncio.get_event_loop().run_until_complete(clientRun())

    asyncio.run(clientRun())
